package com.pxxy.cels.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.pxxy.cels.dao.NoteBookDao;
import com.pxxy.cels.dao.impl.NoteBookImpl;
import com.pxxy.cels.entity.NoteBook;
import com.pxxy.cels.service.INoteBookService;

/**
 * @program: Cels
 * @package: qikran.cels.service.impl
 * @description: ${description}
 * @author: qi_kran
 * @create: 2020-04-07 22:59
 **/
public class NoteBookServiceImpl implements INoteBookService {
	
    private NoteBookDao noteBookDao = new NoteBookImpl();

    @Override
    public List<NoteBook> getNoteBook() throws ClassNotFoundException, IOException {
        File fileDir = new File(NOTE);
        if (!fileDir.exists()) {
            throw new ClassNotFoundException("文件不存在");
        }
        File file = new File(fileDir, NOTEBOOK);
        if (!file.exists()) {
            throw new ClassNotFoundException("文件不存在");
        }
        List<NoteBook> list = noteBookDao.readFromNoteBook(file);
        Collections.sort(list);
        return list;
    }

    @Override
    public void saveNoteBook(List<NoteBook> noteBookList) throws IOException {
        File fileDir = new File(NOTE);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        File file = new File(fileDir, NOTEBOOK);
        List<NoteBook> list = new ArrayList<>();
        Set<NoteBook> set = new HashSet<>();
        if (!file.exists()) {//不存在 则直接写入文件
            list = noteBookList;
        } else {
            //如果  生词本中  的某个元素 已经答对过一次  如若 在练习生词功能外  又答错了这个单词  那么会覆盖生词本中原有的元素
            // 并且会把正确次数清0
            set.addAll(noteBookDao.readFromNoteBook(file));
            set.addAll(noteBookList);
            list.addAll(set);
        }
        noteBookDao.writeToNoteBook(list, file);
    }

    @Override
    public void saveNoteBookByReview(List<NoteBook> noteBookList) throws IOException {
        File fileDir = new File(NOTE);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        File file = new File(fileDir, NOTEBOOK);
        noteBookDao.writeToNoteBook(noteBookList, file);
    }
}
